# -*- coding: utf-8 -*-
# author: sixmillions
# date: 2022/04/18

"""
SHA加密解密示例
https://wenku.baidu.com/view/cd8c0527dd80d4d8d15abe23482fb4daa48d1d50.html
https://blog.csdn.net/qq_41621362/article/details/102105642

# 如果报错：ValueError: No PEM start marker "b'-----BEGIN RSA PUBLIC KEY-----'" found
openssl rsa -in private.pem -RSAPublicKey_out -out pubkey.pem
> https://www.pythonheidong.com/blog/article/139768/e8fc45829a87a158840b/
"""
import rsa

# 密钥生成
pubkey, privkey = rsa.newkeys(1024)

# 保存密钥
with open('public.pem', 'w+') as f:
    f.write(pubkey.save_pkcs1().decode())
with open('private.pem', 'w+') as f:
    f.write(privkey.save_pkcs1().decode())

# 导入密钥
with open("public.pem", 'r') as f:
    pubkey = rsa.PublicKey.load_pkcs1(f.read().encode('utf-8'))
with open("private.pem", 'r') as f:
    privkey = rsa.PrivateKey.load_pkcs1(f.read().encode('utf-8'))

# 待加密明文
message = "hello"
# 公钥加密
crypto = rsa.encrypt(message.encode('utf-8'), pubkey)
print(crypto)
# 私钥解密
de_message = rsa.decrypt(crypto, privkey).decode()
print(de_message)
